package bingo.rpc.framework.cluster.impl;

import bingo.rpc.framework.cluster.ClusterStrategy;
import bingo.rpc.framework.model.ProviderService;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 加权轮询负载均衡算法
 *
 * @author hujinsheng
 * @project bingo
 * @create 2017-12-14 14:52
 **/
public class WeigthRoundRobinClusterStrategyImpl implements ClusterStrategy {
    //计数器
    private int index = 0;
    //计数器锁
    private Lock lock = new ReentrantLock();

    @Override
    public ProviderService select(List<ProviderService> providerServices) {
        ProviderService provider = null;
        List<ProviderService> providerServiceList = Lists.newArrayList();
        try {
            lock.tryLock(10, TimeUnit.MILLISECONDS);
            for (ProviderService providerService : providerServices) {
                int weight = providerService.getWeight();
                for (int i = 0; i < weight; i++) {
                    providerServiceList.add(providerService.copy());
                }
            }
            if (index >= providerServiceList.size()) {
                index = 0;
            }
            provider = providerServiceList.get(index);
            index++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


        return provider;
    }
}
